package com.sf.dlb.controller;


import com.sf.dlb.bean.WalletRquestBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.TokenEntity;
import com.sf.dlb.service.ETHWalletService;
import com.sf.dlb.service.UserDlbRecordService;
import com.sf.dlb.service.UserWalletService;
import com.sf.dlb.service.WalletTopupService;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.RegexUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 钱包
 * Created by jing.tan on 2018/12/10.
 */
@RestController
@RequestMapping("/v1/wallet")
public class WalletController extends BaseController{
    private static Logger logger = LoggerFactory.getLogger(WalletController.class);

    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private ETHWalletService ethWalletService;
    @Autowired
    private WalletTopupService walletTopupService;
    @Autowired
    private UserDlbRecordService userDlbRecordService;

    /**
     * 4.15.	dlb解锁（加密）
     */
    @PostMapping(value = "/unlock")
    @ResponseBody
    public Object unlock(HttpServletRequest request,@RequestBody()WalletRquestBean walletRquestBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==walletRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("unlock request json === " + GsonUtils.getInstance().toJson(walletRquestBean));
        String lockType=walletRquestBean.getLockType();
        if(StringUtils.isBlank(lockType)){
            return ResultVOUtil.error(ResponseConstant.ERROR, "缺少锁类型参数");
        }
        if(null==walletRquestBean.getUnlockCount()||walletRquestBean.getUnlockCount()<=0){
            return ResultVOUtil.error(ResponseConstant.ERROR, "申请数量输入有误");
        }
        if(!RegexUtils.checkIntegerNumber(walletRquestBean.getUnlockCount().toString())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "申请数量请输入整数");
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        walletRquestBean.setUserId(tokenEntity.getUserId());
        if(lockType.equals(ResponseConstant.apply_lock_dlb)){
            resultVO=userWalletService.applylockDlb(walletRquestBean);
        }else{
            resultVO=userWalletService.applyUnlockDlb(walletRquestBean);
        }
        logger.info("unlock response json " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 获取解锁列表
     */
    @PostMapping(value = "/unlockList")
    @ResponseBody
    public Object unlockList(HttpServletRequest request,@RequestBody()WalletRquestBean walletRquestBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==walletRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("unlockList request json === " + GsonUtils.getInstance().toJson(walletRquestBean));
        if(walletRquestBean.getCurrentPages()!=0){
            walletRquestBean.setCurrentPages(walletRquestBean.getCurrentPages()-1);//从0开始算；
        }
        if(walletRquestBean.getPageSize()==0){
            walletRquestBean.setPageSize(20);//默认20条
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        walletRquestBean.setUserId(tokenEntity.getUserId());
        resultVO=userWalletService.unlockDlbList(walletRquestBean);
        logger.info("unlockList response json " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 取消解锁
     */
    @PostMapping(value = "/cancelLock")
    @ResponseBody
    public Object cancelLock(HttpServletRequest request,@RequestBody()WalletRquestBean walletRquestBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==walletRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("cancelLock request json === " + GsonUtils.getInstance().toJson(walletRquestBean));
        if(StringUtils.isEmpty(walletRquestBean.getLockNumber())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数输入有误");
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        walletRquestBean.setUserId(tokenEntity.getUserId());
        resultVO=userWalletService.cancelLock(walletRquestBean);
        logger.info("cancelLock response json " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 4.18.	dlb提现（加密）
     */
    @PostMapping(value = "/extract")
    @ResponseBody
    public Object extract(HttpServletRequest request,@RequestBody WalletRquestBean walletRquestBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==walletRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("unlock request json === " + GsonUtils.getInstance().toJson(walletRquestBean));
        if(StringUtils.isBlank(walletRquestBean.getExtractAddress())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "地址填写不合法");
        }
        if(!walletRquestBean.getExtractAddress().startsWith("0x")
                ||walletRquestBean.getExtractAddress().length()<42){
            return ResultVOUtil.error(ResponseConstant.ERROR, "地址填写有误");
        }
        if(null!=walletRquestBean.getExtractCount()
                &&walletRquestBean.getExtractCount()<global.wallet_extract_least_number){
            return ResultVOUtil.error(ResponseConstant.ERROR, "提取数量不能小于手续费");
        }
        if(!RegexUtils.checkIntegerNumber(walletRquestBean.getExtractCount().toString())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "提取数量请输入整数");
        }
        if(StringUtils.isBlank(walletRquestBean.getValidationCode())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "验证码填写有误");
        }
        if(StringUtils.isBlank(walletRquestBean.getPayPassword())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "支付密码填写有误");
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        walletRquestBean.setUserId(tokenEntity.getUserId());
        resultVO=userWalletService.extractDlb(walletRquestBean);
        logger.info("unlock response json " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 获取提取记录
     */
    @PostMapping(value = "/extractList")
    @ResponseBody
    public Object extractList(HttpServletRequest request,@RequestBody()WalletRquestBean walletRquestBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==walletRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("extractList request json === " + GsonUtils.getInstance().toJson(walletRquestBean));
        if(walletRquestBean.getCurrentPages()!=0){
            walletRquestBean.setCurrentPages(walletRquestBean.getCurrentPages()-1);//从0开始算；
        }
        if(walletRquestBean.getPageSize()==0){
            walletRquestBean.setPageSize(20);//默认20条
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        walletRquestBean.setUserId(tokenEntity.getUserId());
        resultVO=userWalletService.extractDlbList(walletRquestBean);
        logger.info("extractList response json " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 验证提现地址
     */
    @GetMapping(value = "/chekoutExtractAddress/{address}")
    @ResponseBody
    public Object chekoutExtractAddress(HttpServletRequest request,@PathVariable String address) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        logger.info("chekoutExtractAddress start address " + address);
        //判断参数是否合法
        if (StringUtils.isBlank(address)) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        boolean addressFlag=ethWalletService.chckoutExtractAddress(address);
        logger.info("chekoutExtractAddress end addressFlag " + addressFlag);
        if(!addressFlag){
            return ResultVOUtil.error(ResponseConstant.ERROR, "提现地址不合法");
        }
        return ResultVOUtil.success();
    }
    /**
     * 充值记录
     */
    @GetMapping(value = "/topupRecord/{page}/{size}")
    @ResponseBody
    public Object topupRecord(HttpServletRequest request,@PathVariable("page") int page,@PathVariable("size") int size) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        logger.info("topupRecord request page={},size={} ",page,size);
        if(page!=0){
            page=page-1;//从0开始算；
        }
        if(size==0){
            size=20;//默认20条
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        ResultVO resultVO1=walletTopupService.list(tokenEntity.getUserId(),page,size);
        logger.info("topupRecord response {} ",GsonUtils.getInstance().toJson(resultVO1));
        return resultVO1;
    }
    /**
     * 账单详情
     */
    @GetMapping(value = "/billDetails/{page}/{size}")
    @ResponseBody
    public Object billDetails(HttpServletRequest request,@PathVariable("page") int page,@PathVariable("size") int size) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        logger.info("billDetails request page={},size={} ",page,size);
        if(page!=0){
            page=page-1;//从0开始算；
        }
        if(size==0){
            size=20;//默认20条
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        ResultVO resultVO1=userDlbRecordService.list(tokenEntity.getUserId(),page,size);
        logger.info("billDetails response {} ",GsonUtils.getInstance().toJson(resultVO1));
        return resultVO1;
    }
}
